#include "realize2.h"

//---------------------------------------------------------------------------------------------
realize2::realize2() :m_workThread(std::thread(&realize2::loop, this)), m_continue(true), m_freeShutDown(true)
{

}

//---------------------------------------------------------------------------------------------
realize2::~realize2()
{
	{
		std::unique_lock<std::mutex> lock(m_mut);
		m_continue = false;
		m_condition.notify_one();
	}

	if (m_workThread.joinable())
	{
		m_workThread.join();
	}
}

//---------------------------------------------------------------------------------------------
//void realize2::enqueue(funcType fun)
//{
//	std::unique_lock<std::mutex> lock(m_mut);
//	m_queue.push(fun);
//	m_condition.notify_one();
//}
//
////---------------------------------------------------------------------------------------------
//realize2::funcType realize2::dequeue()
//{
//
//	/*funcType fun;
//
//	do {
//		std::unique_lock<std::mutex> lock(m_mut);
//		if (m_queue.empty()) {
//			if (!m_continue) {
//				throw realize2NoElement("no Element");
//				break;
//			}
//
//			m_condition.wait(lock);
//		}
//		else {
//
//			if (!m_continue) {
//				if (m_freeShutDown) {}
//				else {
//					throw realize2NoElement("no Element");
//					break;
//				}
//			}
//			fun = m_queue.front();
//			m_queue.pop();
//			
//		}
//	} while (1);
//
//
//	return fun;*/
//	return funcType();
//}

//---------------------------------------------------------------------------------------------
void realize2::loop()
{

	do {
		std::unique_lock<std::mutex> lock(m_mut);
		if (m_queue.empty()) {
			if (!m_continue) {
				break;
			}
			m_condition.wait(lock);
		}
		else {
			std::optional<std::function<void()>> func;
			func = std::move(m_queue.front());
			m_queue.pop();
			lock.unlock();
			if (func.has_value()) {
				func.value()();
			}

		}
	} while (1);



}
